package com.google.code.sharecontent.action;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.Begin;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.async.CronSchedule;
import org.jboss.seam.core.Events;

import com.google.code.sharecontent.model.Column;

@Scope(ScopeType.CONVERSATION)
@Name("adminAction")
public class AdminAction extends BaseAction {

	private List<Column> tableColumns;
	private List<List<String>> tableResults;
	
	@In("daoAction")
	private DaoAction daoAction;

	private String sqlQuery;

	@Begin
	public void start() {
		
	}
	
	public void runSql() {
		if (this.sqlQuery != null && this.sqlQuery.length()>0) {
		Connection connection = this.daoAction.getConnection();
		try {
			PreparedStatement preparedStatement = connection.prepareStatement(this.sqlQuery);
			ResultSet rs = preparedStatement.executeQuery();
			ResultSetMetaData metaData = rs.getMetaData();
			int columnCount = metaData.getColumnCount();
			tableColumns = new ArrayList<Column>();
			for (int i=1;i<=columnCount;++i) {
//				log.info(""+i+" "+metaData.getColumnName(i)+" \t "+metaData.getColumnTypeName(i));
				Column column = new Column();
				column.setId(i);
				column.setName(metaData.getColumnName(i));
				column.setType(metaData.getColumnTypeName(i));
				tableColumns.add(column);
			}
			tableResults = new ArrayList<List<String>>();
			while (rs.next()) {
				List<String> row = new ArrayList<String>();
				for (int i=1;i<=tableColumns.size();++i) {
					row.add(""+rs.getObject(i));
				}
				tableResults.add(row);
			}
		} catch (SQLException e) {
			//FIXME сделать вывод сообщения об ошибке
			log.info(e.getMessage());
//			e.printStackTrace();
		}
		}
	}
	
	public void startScan() {
		Events.instance().raiseAsynchronousEvent("ResourceScanner");
	}


	public String getSqlQuery() {
		return sqlQuery;
	}

	public void setSqlQuery(String sqlQuery) {
		this.sqlQuery = sqlQuery;
	}
	
	public List<Column> getTableColumns() {
		return this.tableColumns;
	}
	
	public List<List<String>> getTableResults() {
		return this.tableResults;
	}
}
